﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BSPTree
{
    class BSPNode
    {
        BSPNode parent;
        public BSPNode[] children = new BSPNode[2];
        public BSPNode sister;
        public delegate void NodeCreatedEventHandle(BSPNode newNode);
        public event NodeCreatedEventHandle NodeCreated;

        int ID;
        static int NextID = 0;

        public BSPNode(BSPNode parent)
        {
            this.parent = parent;
            ID = BSPNode.NextID;
            BSPNode.NextID += 1;
            //need to make sure the child node remembers the callers on the event
            if(parent != null) this.NodeCreated = parent.NodeCreated;
        }

        public void SplitNode()
        {
            //create nodes and assign parent
            children[0] = new BSPNode(this);
            children[1] = new BSPNode(this);
            //assign sisters
            children[0].sister = children[1].sister;
            children[1].sister = children[0].sister;
            //notify anyone who cares (like the owning tree) that a new node was created
            if (NodeCreated != null)
            {
                NodeCreated(children[0]);
                NodeCreated(children[1]);
            }
        }

        public void Report()
        {
            string msg = string.Format("Node: {0} ", ID);
            if (children[0] == null) msg = msg + " is a leaf.";
            else msg = msg + "is not a leaf";
            Console.WriteLine(msg);
        }
    }
}
